<?php

declare(strict_types=1);

namespace app\api\controller;

use app\common\model\FeedbackModel;
use think\Request;
use think\response\Json;

class Feedback extends Controller
{
    // 允许未登录提交（有 token 则识别 uid）
    protected array $middleware = [
        'orCheck' => ['only' => ['submit']],
    ];

    public function types(): Json
    {
        $list = [
            ['id' => 0, 'name' => '功能异常'],
            ['id' => 1, 'name' => '产品建议'],
            ['id' => 2, 'name' => '违规举报'],
        ];
        return success('success', $list);
    }

    public function submit(Request $request): Json
    {
        $scene   = (int) $request->post('scene', -1);
        $content = trim((string) $request->post('content', ''));
        $images  = $request->post('images', []); // 数组或逗号分隔字符串
        $contact = trim((string) $request->post('contact', ''));

        // 基础校验
        if (!in_array($scene, [0, 1, 2], true)) {
            return error('请选择问题发生的场景');
        }
        $len = mb_strlen($content);
        if ($len < 1 || $len > 200) {
            return error('请填写1-200字的问题与意见');
        }

        // 规范化 images（最多4张）
        if (is_array($images)) {
            if (count($images) > 4) {
                return error('相关截图最多上传4张');
            }
            $images = array_values(array_filter(array_map('strval', $images)));
            $imagesVal = json_encode($images, JSON_UNESCAPED_UNICODE);
        } else {
            // 兼容字符串（逗号分隔）
            $arr = array_filter(array_map('trim', explode(',', (string)$images)));
            if (count($arr) > 4) {
                return error('相关截图最多上传4张');
            }
            $imagesVal = json_encode(array_values($arr), JSON_UNESCAPED_UNICODE);
        }

        $data = [
            'user_id' => $request->uid ?: null,
            'scene'   => $scene,
            'content' => $content,
            'images'  => $imagesVal,
            'contact' => $contact ?: null,
            'ip'      => $request->ip(),
            'ua'      => $request->server('HTTP_USER_AGENT') ?: ($request->header('User-Agent') ?? ''),
            'status'  => 0,
        ];

        $res = (new FeedbackModel())->save($data);
        if (!$res) {
            return error('提交失败，请稍后重试');
        }
        return success('提交成功');
    }
}

